import { login, logout } from '@/api/user'
import { getToken, parseToken, removeToken, getUserInfo } from '@/utils/auth'
import { resetRouter } from '@/router'
import store from "@/store";
import Cookies from "js-cookie";


// 获取默认状态
const getDefaultState = () => {
    const token = getToken();
    const user = getUserInfo();

    return {
        token: token,
        uid: user.uid,
        name: user.name,
        avatar: user.avatar
    };
};

const state = getDefaultState();

// 改变state中数据的值
const mutations = {
    RESET_STATE: (state) => {
        // 重置状态
        Object.assign(state, getDefaultState());
        /**
         * Object.assign(target, source1, source2, ...) 
         * - 方法用于将所有可枚举属性的值从一个或多个源对象source复制到目标对象。它将返回目标对象target
         * - 如果目标对象与源对象有同名属性，或多个源对象有同名属性，则后面的属性会覆盖前面的属性
         * 例如：
         *      const target = { a: 1, b: 1 }
         *      const source1 = { b: 2, c: 2 }
         *      const source2 = { c: 3 }
         *      Object.assign(target, source1, source2)
         *      target // {a:1, b:2, c:3}
         */
    },
    SET_TOKEN: (state, token) => {
        // 设置token
        state.token = token;
        store.commit('user/SET_USER', parseToken(token));
    },
    SET_USER: (state, user) => {
        state.uid = user.uid;
        state.name = user.username;
        state.avatar = user.avatar;
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar;
        Cookies.set("avatar", avatar);
    },
    SET_NAME: (state, name) => {
        state.name = name;
        Cookies.set("name", name);
    }
}

const actions = {
    // 用户登录
    // 存疑：或许应该再登录页面写登录
    login({ commit }, userInfo) {
        /**
         * 解构赋值，把userInfo的account属性赋值给左侧account变量
         * 详情参考：https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
         */
        const { account, password } = userInfo;

        return new Peromise((resolve, reject) => {
            // 执行登录请求
            login(this.qs.stringify({ account, password })).then(response => {
                // 约定后端返回的json对象为：
                // { code: 200, }
                console.log(reponse);

            })
        })
    },
    logout({ commit, state }) {
        return new Promise((resovle, reject) => {
            // 【疑问】退出登录需要传入token么
            logout(state.token).then(() => {
                // 退出登录后，清除token，重置路由和状态
                removeToken();
                resetRouter();
                commit('RESET_STATE');
                resovle();
            }).catch(error => {
                reject(error);
            })
        });
    },
    resetToken({ commit }) {
        return new Promise(resovle => {
            removeToken();
            commit('REST_STATE');
            resovle();
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}